<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 搜索与添加 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList()"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList()"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisiBle = true"
            >添加按钮</el-button
          >
        </el-col>
      </el-row>
      <el-table :data="userlist" style="width: 100%" border stripe>
        <el-table-column type="index" label="#" width="50"></el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="mobile"
          label="电话"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="role_name"
          label="角色"
          width="180"
        ></el-table-column>

        <el-table-column label="状态" width="180">
          <!-- 这里可以使用 v-slot="scope" -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="userStateChanged(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column prop="" label="操作" width="180px">
          <template v-slot="scope">
            <!-- 修改 -->
            <el-tooltip
              effect="dark"
              content="修改角色权限"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini "
                @click="modificationgetIdData(scope.row)"
              ></el-button>
            </el-tooltip>
            <!-- 删除 -->
            <el-tooltip
              effect="dark"
              content="删除角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="danger "
                icon="el-icon-delete"
                size="mini "
                @click="userDel(scope.row)"
              ></el-button>
            </el-tooltip>
            <!-- 分配 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning "
                icon="el-icon-s-tools"
                size="mini "
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <!--  @size-change 一页显示多少个 page-size变化时会触发这里的方法-->
      <!-- :current-change 一共有多少页 current-page 变化时会触发这里的方法-->
      <!-- :current-page 当前第几页-->
      <!-- :page-size 当前页数显示多少条数据 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next ,jumper"
        :total="total"
      >
      </el-pagination>
      <!-- 添加用户弹出页 -->
      <el-dialog title="提示" :visible.sync="addDialogVisiBle" width="30%">
        <!-- 弹窗主体内容 -->
        <el-form ref="addFormRef" :model="addForm" label-width="80px">
          <el-form-item label="用户名称">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="用户密码">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 弹窗页脚 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisiBle = false">取 消</el-button>
          <el-button type="primary" @click="conForm()">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改用户信息弹出页 -->
      <el-dialog
        title="用户修改"
        :visible.sync="modificationDialogVisiBle"
        width="30%"
      >
        <!-- 弹窗主体内容 -->
        <el-form
          ref="modificationFormRef"
          :model="modificationForm"
          label-width="80px"
        >
          <el-form-item label="用户">
            <el-input
              v-model="modificationForm.username"
              :disabled="true"
            ></el-input>
          </el-form-item>
          <el-form-item label="角色ID">
            <el-input v-model="modificationForm.role_id"></el-input>
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="modificationForm.mobile"></el-input>
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="modificationForm.email"></el-input>
          </el-form-item>
        </el-form>
        <!-- 弹窗页脚 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="modificationDialogVisiBle = false"
            >取 消</el-button
          >
          <el-button type="primary" @click="submitUser()">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分配权限弹窗 -->
      <el-dialog
        title="修改权限"
        :visible.sync="setRoleDialogVisible"
        width="30%"
        @close="setRoleDialogClosed()"
      >
        <!-- 主体信息 -->
        <div>
          <p>当前的用户:{{ userInfo.username }}</p>
          <p>当前的角色:{{ userInfo.role_name }}</p>
          <p>要分配的角色:</p>
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesInfo"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </div>
        <!-- 页脚 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveRoleInfo(userInfo.id)"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "Users",
  data() {
    return {
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 10,
      },
      //用户数据:名字,邮箱等
      userlist: [],
      //一共有多少数据
      total: 0,
      // 控制添加用户的弹窗是否弹出
      addDialogVisiBle: false,
      // 添加用户的弹窗表单数据
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      //控制修改用户的弹窗是否弹出
      modificationDialogVisiBle: false,
      //控制修改权限的弹窗是否弹出
      setRoleDialogVisible: false,
      //修改用户弹框信息
      modificationForm: {},
      // 定义一个空对象 等待赋值
      userInfo: "",
      rolesInfo: [],
      // 已选择的角色ID值
      selectedRoleId: "",
    };
  },

  created() {
    this.getUserList();
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        //可以为空 如果是空的话就是搜索全部
        //如果有数值 则搜索对应数值
        params: this.queryInfo,
      });
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取用户列表失败");
      } else {
        this.userlist = res.data.users;
        this.total = res.data.total;
      }
      console.log(this.userlist);
      console.log(this);
    },

    // 一页显示多少个数  newSize
    handleSizeChange(newSize) {
      console.log("一页显示" + newSize);
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    //页数
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },

    // 用户状态修改
    async userStateChanged(userinfo) {
      console.log(userinfo);
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      );
      if (res.meta.status != 200) {
        this.$message.error("状态修改失败");
        userinfo.mg_state = !userinfo.mg_state;
      } else {
        this.$message.success("状态修改成功");
      }
    },

    async conForm() {
      console.log(this.addForm);
      this.addDialogVisiBle = false;
      const { data: res } = await this.$http.post("users", this.addForm);
      console.log(res);
      if (res.meta.status != 201) {
        this.$message.error("账户创建失败");
      } else {
        this.$message.success("创建成功");
        // 清空弹窗输入
        this.addForm = {};
        // 搜索一次全局并渲染
        this.queryInfo.query = "";
        this.getUserList();
      }
    },
    // 根据 ID 查询用户信息 并赋值给modificationForm
    async modificationgetIdData(userinfo) {
      const { data: res } = await this.$http.get(`users/${userinfo.id}`);
      this.modificationForm = res.data;
      this.modificationDialogVisiBle = true;
    },

    //修改用户提交按钮
    async submitUser() {
      console.log(this.modificationForm);
      this.modificationDialogVisiBle = false;
      const { data: res } = await this.$http.put(
        `users/${this.modificationForm.id}`,
        this.modificationForm
      );
      if (res.meta.status != 200) {
        this.$message.error("更新失败");
      } else {
        this.$message.success("更新成功");
        this.getUserList();
      }
    },

    //删除账户按钮
    async userDel(userinfo) {
      const { data: res } = await this.$http.delete(`users/${userinfo.id}`);
      if (res.meta.status != 200) {
        this.$message.error("账户删除失败");
      } else {
        this.$message.success(userinfo.username + "删除成功");
        this.getUserList();
      }
    },
    // 分配角色弹框
    async setRole(userInfo) {
      this.userInfo = userInfo;

      // 获取所有的角色列表
      const { data: res } = await this.$http.get("roles");
      this.rolesInfo = res.data;

      this.setRoleDialogVisible = true;
    },
    async saveRoleInfo(usersId) {
      console.log(usersId);
      console.log(this.selectedRoleId);
      if (!this.selectedRoleId) {
        this.$message.error("角色");
      } else {
        const { data: res } = await this.$http.put(`users/${usersId} /role`, {
          rid: this.selectedRoleId,
        });
        if (res.meta.status != 200) {
          this.$message.error("修改角色失败");
        } else {
          this.$message.success("修改成功");
          this.getUserList();
        }
      }

      this.setRoleDialogVisible = false;
    },

    // 监听分配权限的关闭事件
    setRoleDialogClosed() {
      this.selectedRoleId = "";
      this.userInfo = {};
    },
  },
};
</script>

<style>
.el-table {
  text-align: center;
}
</style>